﻿using System;
using System.Linq;
using System.Web.DynamicData;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Fatec.ControleEstoque.Attributes.Templates;
using System.Data.Linq;

namespace Fatec.ControleEstoque.Interface
{

    public partial class ChildrenGrid_EditField : FieldTemplateUserControl
    {
        protected MetaTable table;

        public Boolean EnableDelete { get; set; }
        public Boolean EnableInsert { get; set; }
        public Boolean EnableUpdate { get; set; }

        private String[] DisplayColumns { get; set; }

        public ChildrenGrid_EditField()
        {
            // set default values
            EnableDelete = true;
            EnableUpdate = true;
            EnableInsert = true;
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            var metaChildColumn = Column as MetaChildrenColumn;
            var attribute = Column.Attributes.OfType<ShowColumnsAttribute>().SingleOrDefault();

            if (attribute != null)
            {
                if (!attribute.EnableDelete)
                    EnableDelete = false;
                if (!attribute.EnableUpdate)
                    EnableUpdate = false;
                if (attribute.DisplayColumns.Length > 0)
                    DisplayColumns = attribute.DisplayColumns;
            }

            var metaForeignKeyColumn = metaChildColumn.ColumnInOtherTable as MetaForeignKeyColumn;

            if (metaChildColumn != null && metaForeignKeyColumn != null)
            {
                GridDataSource.ContextTypeName = metaChildColumn.ChildTable.DataContextType.FullName;

                GridDataSource.EntitySetName  = metaChildColumn.ChildTable.Name;

                // enable update, delete and insert
                GridDataSource.EnableDelete = EnableDelete;
                GridDataSource.EnableInsert = EnableInsert;
                GridDataSource.EnableUpdate = EnableUpdate;
                GridView1.AutoGenerateDeleteButton = EnableDelete;
                GridView1.AutoGenerateEditButton = EnableUpdate;
                
                // get an instance of the MetaTable
                table = GridDataSource.GetTable();

                // Generate the columns as we can't rely on 
                // DynamicDataManager to do it for us.
                GridView1.ColumnsGenerator = new FieldTemplateRowGenerator(table, DisplayColumns);

                // setup the GridView's DataKeys
                String[] keys = new String[metaChildColumn.ChildTable.PrimaryKeyColumns.Count];
                int i = 0;
                foreach (var keyColumn in metaChildColumn.ChildTable.PrimaryKeyColumns)
                {
                    keys[i] = keyColumn.Name;
                    i++;
                }
                GridView1.DataKeyNames = keys;
                
                //GridDataSource.AutoGenerateWhereClause = true;
            }
            else
            {
                // throw an error if set on column other than MetaChildrenColumns
                throw new InvalidOperationException("The GridView FieldTemplate can only be used with MetaChildrenColumns");
            }
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            var metaChildrenColumn = Column as MetaChildrenColumn;
            var metaForeignKeyColumn = metaChildrenColumn.ColumnInOtherTable as MetaForeignKeyColumn;

            // get the association attributes associated with MetaChildrenColumns
            
            var association = metaChildrenColumn.Attributes.
                OfType<System.Data.Linq.Mapping.AssociationAttribute>().FirstOrDefault();
                       

            if (metaForeignKeyColumn != null && association != null)
            {
                // get keys ThisKey and OtherKey into Pairs
                var keys = new Dictionary<String, String>();
                var seperator = new char[] { ',' };
                var thisKeys = association.ThisKey.Split(seperator);
                var otherKeys = association.OtherKey.Split(seperator);
                for (int i = 0; i < thisKeys.Length; i++)
                {
                    keys.Add(otherKeys[i], thisKeys[i]);
                }

                // setup the where clause 
                // support composite foreign keys
                foreach (String fkName in metaForeignKeyColumn.ForeignKeyNames)
                {
                    // get the current pk column
                    var fkColumn = metaChildrenColumn.ChildTable.GetColumn(fkName);

                    // setup parameter
                    var param = new Parameter();
                    param.Name = fkColumn.Name;
                    param.Type = fkColumn.TypeCode;

                    // get the PK value for this FK column using the fk pk pairs
                    param.DefaultValue = Request.QueryString[keys[fkName]];

                    // add the where clause
                    GridDataSource.WhereParameters.Add(param);
                }
            }
            else if (metaForeignKeyColumn != null)
            {
              String fkName = metaForeignKeyColumn.ParentTable.Name;
              // get the current pk column
              var fkColumn = metaChildrenColumn.ChildTable.GetColumn(fkName);

              // setup parameter
              var param = new Parameter();
              param.Name = fkColumn.Name;
              param.Type = fkColumn.TypeCode;

              // get the PK value for this FK column using the fk pk pairs
              param.DefaultValue = Request.QueryString["Id"];

              // add the where clause
              GridDataSource.Where = fkColumn.SortExpression + (param.DefaultValue == null ? " < 0" : " = " + param.DefaultValue);
            }

            // doing the work of this above because we can't
            // set the DynamicDataManager table or where values
            //DynamicDataManager1.RegisterControl(GridView1, false);
        }
    }
}